<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>深入探索Java中的ReentrantLock | 坤个人博客</title><meta name="author" content="Houkl"><meta name="copyright" content="Houkl"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="简介：在多线程编程中，保证线程安全性是非常重要的。Java 提供了多种机制来实现线程同步，其中之一就是使用 ReentrantLock。本文将深入探讨 ReentrantLock 的原理、使用方法，并附带使用示例和测试验证代码。 ReentrantLock 的原理和特点ReentrantLock 是 Java.util.concurrent 包下的一个锁实现，它实现了 Lock 接口。与 sync">
<meta property="og:type" content="article">
<meta property="og:title" content="深入探索Java中的ReentrantLock">
<meta property="og:url" content="http://hkl.gitee.io/houkl/2019/04/03/java/reentrantLock/index.html">
<meta property="og:site_name" content="坤个人博客">
<meta property="og:description" content="简介：在多线程编程中，保证线程安全性是非常重要的。Java 提供了多种机制来实现线程同步，其中之一就是使用 ReentrantLock。本文将深入探讨 ReentrantLock 的原理、使用方法，并附带使用示例和测试验证代码。 ReentrantLock 的原理和特点ReentrantLock 是 Java.util.concurrent 包下的一个锁实现，它实现了 Lock 接口。与 sync">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s1.ax1x.com/2023/06/06/pCiSafs.png">
<meta property="article:published_time" content="2019-04-02T16:00:00.000Z">
<meta property="article:modified_time" content="2019-04-02T16:00:00.000Z">
<meta property="article:author" content="Houkl">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s1.ax1x.com/2023/06/06/pCiSafs.png"><link rel="shortcut icon" href="/houkl/img/favicon.png"><link rel="canonical" href="http://hkl.gitee.io/houkl/2019/04/03/java/reentrantLock/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/houkl/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/houkl/',
  algolia: undefined,
  localSearch: {"path":"/houkl/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '深入探索Java中的ReentrantLock',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2019-04-03 00:00:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = 'hidden';
    document.getElementById('loading-box').classList.remove("loaded")
  }
}

preloader.initLoading()
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s1.ax1x.com/2023/05/31/p9v6spQ.md.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/houkl/archives/"><div class="headline">文章</div><div class="length-num">21</div></a><a href="/houkl/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/houkl/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://s1.ax1x.com/2023/06/06/pCiSafs.png')"><nav id="nav"><span id="blog-info"><a href="/houkl/" title="坤个人博客"><span class="site-name">坤个人博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">深入探索Java中的ReentrantLock</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-04-02T16:00:00.000Z" title="发表于 2019-04-03 00:00:00">2019-04-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2019-04-02T16:00:00.000Z" title="更新于 2019-04-03 00:00:00">2019-04-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/houkl/categories/java/">java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="深入探索Java中的ReentrantLock"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="简介："><a href="#简介：" class="headerlink" title="简介："></a>简介：</h2><p>在多线程编程中，保证线程安全性是非常重要的。Java 提供了多种机制来实现线程同步，其中之一就是使用 ReentrantLock。本文将深入探讨 ReentrantLock 的原理、使用方法，并附带使用示例和测试验证代码。</p>
<h2 id="ReentrantLock-的原理和特点"><a href="#ReentrantLock-的原理和特点" class="headerlink" title="ReentrantLock 的原理和特点"></a>ReentrantLock 的原理和特点</h2><p>ReentrantLock 是 Java.util.concurrent 包下的一个锁实现，它实现了 Lock 接口。与 synchronized 关键字相比，ReentrantLock 提供了更灵活的同步控制。下面是一些 ReentrantLock 的特点：</p>
<ol>
<li>可重入性：与 synchronized 类似，ReentrantLock 支持线程的重入，即同一个线程可以多次获取该锁而不会发生死锁。</li>
<li>公平性：ReentrantLock 提供了公平锁和非公平锁两种模式。在公平模式下，锁会按照线程请求的顺序进行获取，而在非公平模式下，锁的获取是无序的。</li>
<li>条件变量：ReentrantLock 支持 Condition 条件变量的使用，可以通过条件变量实现线程之间的协调和通信。</li>
</ol>
<h2 id="ReentrantLock-的使用示例"><a href="#ReentrantLock-的使用示例" class="headerlink" title="ReentrantLock 的使用示例"></a>ReentrantLock 的使用示例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.Lock;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.ReentrantLock;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ReentrantLockExample</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">Lock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">increment</span><span class="params">()</span> &#123;</span><br><span class="line">        lock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            count++;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">getCount</span><span class="params">()</span> &#123;</span><br><span class="line">        lock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> count;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>在上述示例中，我们创建了一个 ReentrantLock 对象并使用它来实现对 count 变量的同步访问。在 increment() 方法中，我们使用 lock() 方法获取锁，并在 try-finally 块中使用 unlock() 方法释放锁。在 getCount() 方法中同样使用了 lock() 和 unlock() 方法来保证对 count 变量的同步访问。</p>
<h2 id="ReentrantLock-的测试验证代码"><a href="#ReentrantLock-的测试验证代码" class="headerlink" title="ReentrantLock 的测试验证代码"></a>ReentrantLock 的测试验证代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ReentrantLockTest</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">ReentrantLockExample</span> <span class="variable">example</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLockExample</span>();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 创建多个线程对 count 变量进行增加操作</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">0</span>; j &lt; <span class="number">1000</span>; j++) &#123;</span><br><span class="line">                    example.increment();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 主线程等待所有线程执行完毕</span></span><br><span class="line">        Thread.sleep(<span class="number">5000</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 打印最终结果</span></span><br><span class="line">        System.out.println(<span class="string">&quot;Count: &quot;</span> + example.getCount());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述测试代码中，我们创建了多个线程对 count 变量进行增加操作，并在主线程中等待所有线程执行完毕后打印最终结果。通过运行测试代码，我们可以验证 ReentrantLock 的线程安全性和正确性。</p>
<h2 id="升级版本的锁工具细化锁粒度，根据业务和ID进行加锁"><a href="#升级版本的锁工具细化锁粒度，根据业务和ID进行加锁" class="headerlink" title="升级版本的锁工具细化锁粒度，根据业务和ID进行加锁"></a>升级版本的锁工具细化锁粒度，根据业务和ID进行加锁</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> cn.hutool.core.util.StrUtil;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.ConcurrentHashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.ReentrantLock;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 锁的一些工具</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: Houkl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LockUtils</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 锁存对象地址</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConcurrentHashMap&lt;String, ReentrantLock&gt; lockMap = <span class="keyword">new</span> <span class="title class_">ConcurrentHashMap</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@description</span>:执行锁方法 根据业务类型以及 id加锁，细化锁粒度提高程序执行效率</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@author</span>: Houkl</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@version</span> 1.0</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">syc</span><span class="params">(String business,String key,SycCallBak sycCallBak)</span> <span class="keyword">throws</span> RuntimeException&#123;</span><br><span class="line">        <span class="keyword">if</span>(StrUtil.isBlank(business) || StrUtil.isBlank(key))<span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;锁失败business或key is null&quot;</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">id</span> <span class="operator">=</span> business+<span class="string">&quot;:&quot;</span>+key;</span><br><span class="line">        <span class="type">ReentrantLock</span> <span class="variable">o</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (o != <span class="literal">null</span>) &#123;</span><br><span class="line">                o.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">            o = lockMap.computeIfAbsent(id, k -&gt; <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>());</span><br><span class="line">            o.lock();</span><br><span class="line">            <span class="comment">//新创建的被上一个线程remove掉了，或者新创建的对象和lockMap中已有的不是同一个对象，重试</span></span><br><span class="line">        &#125; <span class="keyword">while</span> (lockMap.get(id) == <span class="literal">null</span> || o != lockMap.get(id));</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            sycCallBak.callBak();</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e.getMessage());</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            lockMap.remove(id);</span><br><span class="line">            <span class="keyword">if</span>(o != <span class="literal">null</span>)o.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@FunctionalInterface</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">SycCallBak</span>&#123;</span><br><span class="line">        <span class="keyword">void</span> <span class="title function_">callBak</span><span class="params">()</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/***********测试************/</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span> count;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">thread1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            <span class="comment">//假设业务为 test_1 id 为 1</span></span><br><span class="line">            LockUtils.syc(<span class="string">&quot;TEST_1&quot;</span>, <span class="string">&quot;1&quot;</span>, () -&gt;&#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">k</span> <span class="operator">=</span> <span class="number">0</span>; k &lt; <span class="number">100000</span>; k++) &#123;</span><br><span class="line">                    count++;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">thread2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            LockUtils.syc(<span class="string">&quot;TEST_1&quot;</span>, <span class="string">&quot;1&quot;</span>, () -&gt;&#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">k</span> <span class="operator">=</span> <span class="number">0</span>; k &lt; <span class="number">100000</span>; k++) &#123;</span><br><span class="line">                    count++;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">        thread1.start();</span><br><span class="line">        thread2.start();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 等待两个线程都运行结束后，再打印结果</span></span><br><span class="line">            thread1.join();</span><br><span class="line">            thread2.join();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//期待结果是200000，线程如果不安全但是结果会小于这个值</span></span><br><span class="line">        System.out.println(count);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/***********测试************/</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文介绍了 ReentrantLock 的原理、使用方法，并提供了示例代码和测试验证代码。通过使用 ReentrantLock，我们可以实现更灵活的线程同步控制，保证多线程环境下的数据安全性。希望本文能帮助读者更好地理解和应用 ReentrantLock，编写出高效且线程安全的代码。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://hkl.gitee.io/houkl">Houkl</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://hkl.gitee.io/houkl/2019/04/03/java/reentrantLock/">http://hkl.gitee.io/houkl/2019/04/03/java/reentrantLock/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://hkl.gitee.io/houkl" target="_blank">坤个人博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://s1.ax1x.com/2023/06/06/pCiSafs.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/houkl/2019/06/28/java/volatile/" title="深入理解Java中的volatile关键字"><img class="cover" src="https://s1.ax1x.com/2023/06/06/pCiS2tJ.png" onerror="onerror=null;src='/houkl/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">深入理解Java中的volatile关键字</div></div></a></div><div class="next-post pull-right"><a href="/houkl/2019/01/26/java/rushToPurchase/" title="用Redis + Lua 实现商品抢购"><img class="cover" src="https://s1.ax1x.com/2023/06/06/pCiSgk4.png" onerror="onerror=null;src='/houkl/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">用Redis + Lua 实现商品抢购</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://s1.ax1x.com/2023/05/31/p9v6spQ.md.jpg" onerror="this.onerror=null;this.src='/houkl/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Houkl</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/houkl/archives/"><div class="headline">文章</div><div class="length-num">21</div></a><a href="/houkl/tags/"><div class="headline">标签</div><div class="length-num">0</div></a><a href="/houkl/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/houkunliang"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">个人博客不定期更新，还望各位看官谅解</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B%EF%BC%9A"><span class="toc-number">1.</span> <span class="toc-text">简介：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ReentrantLock-%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E7%89%B9%E7%82%B9"><span class="toc-number">2.</span> <span class="toc-text">ReentrantLock 的原理和特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ReentrantLock-%E7%9A%84%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B"><span class="toc-number">3.</span> <span class="toc-text">ReentrantLock 的使用示例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ReentrantLock-%E7%9A%84%E6%B5%8B%E8%AF%95%E9%AA%8C%E8%AF%81%E4%BB%A3%E7%A0%81"><span class="toc-number">4.</span> <span class="toc-text">ReentrantLock 的测试验证代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%87%E7%BA%A7%E7%89%88%E6%9C%AC%E7%9A%84%E9%94%81%E5%B7%A5%E5%85%B7%E7%BB%86%E5%8C%96%E9%94%81%E7%B2%92%E5%BA%A6%EF%BC%8C%E6%A0%B9%E6%8D%AE%E4%B8%9A%E5%8A%A1%E5%92%8CID%E8%BF%9B%E8%A1%8C%E5%8A%A0%E9%94%81"><span class="toc-number">5.</span> <span class="toc-text">升级版本的锁工具细化锁粒度，根据业务和ID进行加锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/houkl/2019/06/28/java/volatile/" title="深入理解Java中的volatile关键字"><img src="https://s1.ax1x.com/2023/06/06/pCiS2tJ.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="深入理解Java中的volatile关键字"/></a><div class="content"><a class="title" href="/houkl/2019/06/28/java/volatile/" title="深入理解Java中的volatile关键字">深入理解Java中的volatile关键字</a><time datetime="2019-06-27T16:00:00.000Z" title="发表于 2019-06-28 00:00:00">2019-06-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2019/04/03/java/reentrantLock/" title="深入探索Java中的ReentrantLock"><img src="https://s1.ax1x.com/2023/06/06/pCiSafs.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="深入探索Java中的ReentrantLock"/></a><div class="content"><a class="title" href="/houkl/2019/04/03/java/reentrantLock/" title="深入探索Java中的ReentrantLock">深入探索Java中的ReentrantLock</a><time datetime="2019-04-02T16:00:00.000Z" title="发表于 2019-04-03 00:00:00">2019-04-03</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2019/01/26/java/rushToPurchase/" title="用Redis + Lua 实现商品抢购"><img src="https://s1.ax1x.com/2023/06/06/pCiSgk4.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="用Redis + Lua 实现商品抢购"/></a><div class="content"><a class="title" href="/houkl/2019/01/26/java/rushToPurchase/" title="用Redis + Lua 实现商品抢购">用Redis + Lua 实现商品抢购</a><time datetime="2019-01-25T16:00:00.000Z" title="发表于 2019-01-26 00:00:00">2019-01-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2018/12/15/java/synchronized/" title="深入了解 Java 中的 Synchronized 关键字"><img src="https://s1.ax1x.com/2023/06/06/pCPzDde.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="深入了解 Java 中的 Synchronized 关键字"/></a><div class="content"><a class="title" href="/houkl/2018/12/15/java/synchronized/" title="深入了解 Java 中的 Synchronized 关键字">深入了解 Java 中的 Synchronized 关键字</a><time datetime="2018-12-14T16:00:00.000Z" title="发表于 2018-12-15 00:00:00">2018-12-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/houkl/2018/11/05/middleware/activeMQ/" title="ActiveMQ初见"><img src="https://s1.ax1x.com/2023/06/06/pCPxUHg.png" onerror="this.onerror=null;this.src='/houkl/img/404.jpg'" alt="ActiveMQ初见"/></a><div class="content"><a class="title" href="/houkl/2018/11/05/middleware/activeMQ/" title="ActiveMQ初见">ActiveMQ初见</a><time datetime="2018-11-04T16:00:00.000Z" title="发表于 2018-11-05 00:00:00">2018-11-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Houkl</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/houkl/js/utils.js"></script><script src="/houkl/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/houkl/js/search/local-search.js"></script></div></div></body></html>